package archimede;

import it.sauronsoftware.ftp4j.FTPAbortedException;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferException;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPFile;
import it.sauronsoftware.ftp4j.FTPIllegalReplyException;
import it.sauronsoftware.ftp4j.FTPListParseException;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.geom.Point2D;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
import java.util.Scanner;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import net.miginfocom.swing.MigLayout;

import org.apache.commons.io.FileUtils;


/**
 * Main class, create
 * 
 * @author Alex
 * 
 */
public class StartingWindow {
	/**
	 * frame contenente tutti i pannelli
	 */
	private JFrame window = new JFrame("EUREKA - ARCHIMEDE");
	/**
	 * panel containing tab pages
	 */
	private JPanel projectPanel = new JPanel();
	/**
	 * height of window
	 */
	private int height;
	/**
	 * width of window
	 */
	private int width;
	/**
	 * count RTD in corso
	 */
	private int countRtd = 0;
	/**
	 * count RTD ultimo salvato, utile per il conto quando faccio nuovo
	 */
	private int lastCountRtd = 0;
	/**
	 * nome progetto caricato
	 */
	private String nameProject;
	/**
	 * ultimo percorso aperto per la ricerca di immagini
	 */
	private String lastPath = "";
	/**
	 * tab of pages
	 */
	private JTabbedPane tab = new JTabbedPane();

	/**
	 * menubar contenente i pulsanti SCARICA PROGETTO || APRI PROGETTO || NUOVO || ELIMINA || INVIA || SALVA
	 */
	private JMenuBar menubar = new JMenuBar() {
		/** Stroke size. it is recommended to set it to 1 for better view */
		protected int strokeSize = 1;
		/** Color of shadow */
		protected Color shadowColor = Color.black;
		/** Sets if it drops shadow */
		protected boolean shady = true;
		/** Sets if it has an High Quality view */
		protected boolean highQuality = true;
		/** Double values for Horizzontal and Vertical radius of corner arcs */
		protected Dimension arcs = new Dimension(10, 10);
		/** Distance between border of shadow and border of opaque panel */
		protected int shadowGap = 2;
		/** The offset of shadow. */
		protected int shadowOffset = 4;
		/** The transparency value of shadow. ( 0 - 255) */
		protected int shadowAlpha = 150;

		@Override
		protected void paintComponent(Graphics g) {
			super.paintComponent(g);
			int width = getWidth();
			int height = getHeight();
			int shadowGap = this.shadowGap;
			Graphics2D graphics = (Graphics2D) g;

			graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

			// 2 colori che fanno la sfumatura

			Point2D.Float p1 = new Point2D.Float(0.f, 75.f); // Gradient line
			// start
			Point2D.Float p2 = new Point2D.Float(0.f, 0.f); // Gradient line end
			GradientPaint g1 = new GradientPaint(p1, new Color(143, 143, 143), p2, new Color(220, 243, 243), true);
			graphics.setPaint(g1);
			graphics.fillRoundRect(shadowOffset,// X position
					shadowOffset,// Y position
					width - strokeSize - shadowOffset, // width
					height - strokeSize - shadowOffset, // height
					arcs.width, arcs.height);// arc Dimension

			// Draws the rounded opaque panel with borders.

			graphics.fillRoundRect(0, 0, width - shadowGap, height - shadowGap, arcs.width, arcs.height);
			graphics.setColor(getForeground());
			graphics.setStroke(new BasicStroke(strokeSize));

			graphics.drawRoundRect(0, 0, width - shadowGap, height - shadowGap, arcs.width, arcs.height);

			// Sets strokes to default, is better.
			graphics.setStroke(new BasicStroke());
			// graphics.drawString(getText(), 20, 20);
		}
	};

	/**
	 * APRI PROGETTO
	 */
	private JMenu apriProgetto = new JMenu("APRI PROGETTO");
	/**
	 * username ftp
	 */
	private String username;
	/**
	 * password ftp
	 */
	private String password;

	private BuildingData datiEdificio;
	private Premesse premesse;
	private PuntiRilevazione rilevazione;
	private PuntoCritico critico;
	private Piantina piantina;
	private Sali sali;
	private PotenzialiOrizzontali orizzontali;
	private PotenzialiVerticali verticali;
	private Conclusioni conclusioni;
	private DatiEdificio edificio;
	private Strumenti strumenti;

	public StartingWindow() {

		// ottengo dimensioni schermo
		Rectangle maxBounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
		height = maxBounds.height;
		width = maxBounds.width;
		window.setSize(width, height - 30);
		window.setIconImage(new ImageIcon(ClassLoader.getSystemResource("icon.jpg")).getImage());
		window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		window.addWindowListener(new WindowsClosing());

		// apri progetto in locale
		apriProgetto.setIcon(new ImageIcon(ClassLoader.getSystemResource("apri.png")));
		apriProgetto.setContentAreaFilled(false);
		apriProgetto.setPreferredSize(new Dimension(width / 6, 25));

		// set menubar
		menubar.add(apriProgetto);
		menubar.setPreferredSize(new Dimension(width, 40));
		window.setJMenuBar(menubar);

		avvio();

		projectPanel.setLayout(new MigLayout());
		projectPanel.setPreferredSize(new Dimension(width, height));

		projectPanel.add(tab, "dock north ,gapleft 5, width " + width * 9.4 / 10 + ":" + width * 9.4 / 10 + ":" + width * 9.4 / 10 + ",height "
				+ height * 8 / 10 + ":" + height * 8 / 10 + ":" + height * 8 / 10);
		// tab.setPreferredSize(new Dimension(width, height * 8 / 10));
		window.setContentPane(tab);

		addOption();
		nuovo();
		refresh();

		window.setVisible(true);
	}

	/**
	 * crea cartella di sistema 'ArchimedeSuper' , setta la lista dei progetti del pc , setta il contatore rtd
	 */
	void avvio() {
		// accesso alla cartella di sistema, cancella quanto fatto prima
		Properties pc = System.getProperties();
		String homePath = pc.getProperty("user.home");
		File aa = new File(homePath + pc.getProperty("file.separator") + "ArchimedeSuper");
		if (!aa.exists())
			aa.mkdir();
		setProjectListFromPC();
		setRtd();
	}

	/**
	 * setta il contatore rtd
	 */
	public void setRtd() {
		lastCountRtd = 0;
		Properties pc = System.getProperties();
		String homePath = pc.getProperty("user.home");
		String directoryProject = homePath + pc.getProperty("file.separator") + "ArchimedeSuper";

		// System.out.println("directory : " + directoryProject);
		File root = new File(directoryProject);
		File[] allProject = root.listFiles();
		for (int i = 0; i < allProject.length; i++) {
			// System.out.println("enter for");
			if (allProject[i].isDirectory()) {
				lastCountRtd++;
			}
		}
		lastCountRtd++;
		countRtd = lastCountRtd;
	}

	/**
	 * crea la lista di progetti caricabili nel menu 'Apri progetto' pescati dal proprio pc
	 */
	public void setProjectListFromPC() {
		apriProgetto.removeAll();
		lastCountRtd = 0;
		Properties pc = System.getProperties();
		String homePath = pc.getProperty("user.home");
		String directoryProject = homePath + pc.getProperty("file.separator") + "ArchimedeSuper";

		// System.out.println("directory : " + directoryProject);
		File root = new File(directoryProject);
		File[] allProject = root.listFiles();
		for (int i = 0; i < allProject.length; i++) {
			// System.out.println("enter for");
			if (allProject[i].isDirectory()) {
				if (!allProject[i].getName().contains("_delete")) {
					// System.out.println("** subdirectory : " + allProject[i].getName());
					JMenuItem tp = new JMenuItem(allProject[i].getName());
					// System.out.println("<<"+list[i].getName());
					tp.addActionListener(new LoadProject(allProject[i].getName()));
					apriProgetto.add(tp);
				}
			}

		}
		// refresh();
	}

	/**
	 * crea nuovo progetto
	 */
	public void nuovo() {
		// resetto tutti i valori
		tab.removeAll();
		// inizializza nuovi oggetti
		edificio = new DatiEdificio(StartingWindow.this);
		datiEdificio = new BuildingData(StartingWindow.this, edificio);
		premesse = new Premesse(StartingWindow.this);
		rilevazione = new PuntiRilevazione(StartingWindow.this);
		critico = new PuntoCritico(StartingWindow.this);
		piantina = new Piantina(StartingWindow.this);
		sali = new Sali(StartingWindow.this);
		verticali = new PotenzialiVerticali(StartingWindow.this);
		orizzontali = new PotenzialiOrizzontali(StartingWindow.this);
		conclusioni = new Conclusioni(this);
		strumenti = new Strumenti();

		tab.add("Dati edificio", new JScrollPane(edificio, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
			@Override
			public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
				// TODO Auto-generated method stub
				verticalScrollBar.setUnitIncrement(15);
				super.setVerticalScrollBar(verticalScrollBar);
			}
		});
		tab.add("Premesse", new JScrollPane(premesse, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
			@Override
			public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
				// TODO Auto-generated method stub
				verticalScrollBar.setUnitIncrement(15);
				super.setVerticalScrollBar(verticalScrollBar);
			}
		});
		tab.add("Immobile", new JScrollPane(datiEdificio, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
			@Override
			public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
				// TODO Auto-generated method stub
				verticalScrollBar.setUnitIncrement(15);
				super.setVerticalScrollBar(verticalScrollBar);
			}
		});
		tab.add("Strumenti", new JScrollPane(strumenti, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
			@Override
			public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
				// TODO Auto-generated method stub
				verticalScrollBar.setUnitIncrement(15);
				super.setVerticalScrollBar(verticalScrollBar);
			}
		});
		tab.add("Punti misurazione", rilevazione);
		tab.add("Punti critici", critico);
		tab.add("Pianta con punti", new JScrollPane(piantina, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
			@Override
			public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
				// TODO Auto-generated method stub
				verticalScrollBar.setUnitIncrement(15);
				super.setVerticalScrollBar(verticalScrollBar);
			}
		});
		tab.add("Sali", new JScrollPane(sali, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
			@Override
			public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
				// TODO Auto-generated method stub
				verticalScrollBar.setUnitIncrement(15);
				super.setVerticalScrollBar(verticalScrollBar);
			}
		});
		tab.add("Tensione verticale", new JScrollPane(verticali, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
			@Override
			public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
				// TODO Auto-generated method stub
				verticalScrollBar.setUnitIncrement(15);
				super.setVerticalScrollBar(verticalScrollBar);
			}
		});

		tab.add("Tensione orizzontale", new JScrollPane(orizzontali, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
				JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
			@Override
			public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
				// TODO Auto-generated method stub
				verticalScrollBar.setUnitIncrement(15);
				super.setVerticalScrollBar(verticalScrollBar);
			}
		});
		tab.add("Conclusioni", new JScrollPane(conclusioni, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
			@Override
			public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
				// TODO Auto-generated method stub
				verticalScrollBar.setUnitIncrement(15);
				super.setVerticalScrollBar(verticalScrollBar);
			}
		});

		setRtd();
		countRtd = lastCountRtd;
		window.setTitle("EUREKA SILVER - ARCHIMEDE" + " ~ Progetto " + countRtd);
	}

	/**
	 * metodo ausiliario per ridisegnare la finestra
	 */
	public void refresh() {
		window.paintAll(window.getGraphics());
	}

	/**
	 * aggiunge azioni ai pulsanti
	 */
	public void addOption() {

		// salva in locale i dati, non li invia al server
		JButton salva = new JButton("SALVA", new ImageIcon(ClassLoader.getSystemResource("salva.png")));
		salva.setContentAreaFilled(false);
		salva.setRolloverEnabled(true);
		salva.setToolTipText("Salva il progetto, attendere il messaggio di conferma");
		salva.setRolloverIcon(new ImageIcon(ClassLoader.getSystemResource("salva_roll.png")));
		// invia al server il progetto
		JButton invia = new JButton("INVIA", new ImageIcon(ClassLoader.getSystemResource("invia-file.png")));
		invia.setContentAreaFilled(false);
		invia.setRolloverEnabled(true);
		invia.setToolTipText("Invia il progettto, attendere il messaggio di conferma");
		invia.setRolloverIcon(new ImageIcon(ClassLoader.getSystemResource("invia-file_roll.png")));
		// cancella progetto in locale (crea direcotory vuota per mantenere
		// l'rtd
		JButton elimina = new JButton("ELIMINA", new ImageIcon(ClassLoader.getSystemResource("elimina-file.png")));
		elimina.setContentAreaFilled(false);
		elimina.setRolloverEnabled(true);
		elimina.setToolTipText("Elimina il progetto");
		elimina.setRolloverIcon(new ImageIcon(ClassLoader.getSystemResource("elimina-file_roll.png")));

		// nuovo progetto
		JButton nuovo = new JButton("NUOVO", new ImageIcon(ClassLoader.getSystemResource("nuovo.png")));
		nuovo.setContentAreaFilled(false);
		nuovo.setRolloverEnabled(true);
		nuovo.setToolTipText("Crea un nuovo progetto");
		nuovo.setRolloverIcon(new ImageIcon(ClassLoader.getSystemResource("nuovo_roll.png")));

		// scarica dal server
		JButton download = new JButton("Dowload", new ImageIcon(ClassLoader.getSystemResource("apri.png")));
		download.setContentAreaFilled(false);
		download.setRolloverEnabled(true);
		download.setToolTipText("Scarica progetti dal server");
		download.setRolloverIcon(new ImageIcon(ClassLoader.getSystemResource("apri_roll.png")));

		// dimensioni
		salva.setPreferredSize(new Dimension(width / 6, 25));
		invia.setPreferredSize(new Dimension(width / 6, 25));
		elimina.setPreferredSize(new Dimension(width / 6, 25));
		nuovo.setPreferredSize(new Dimension(width / 6, 25));
		download.setPreferredSize(new Dimension(width / 6, 25));

		// invia al server il progetto
		invia.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// salva in locale
				save();
				Properties pc = System.getProperties();
				String homePath = pc.getProperty("user.home");
				String directoryProject = homePath + pc.getProperty("file.separator") + "ArchimedeSuper" + pc.getProperty("file.separator") + nameProject;
				new InviaProgetto(directoryProject);
			}
		});

		// salva in locale
		salva.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// salva in locale
				if (save())
					JOptionPane.showMessageDialog(null, "Progetto salvato");
				else
					JOptionPane.showMessageDialog(null, "Errore nel salvataggio, riprovare");
				setProjectListFromPC();
			}
		});

		// elimina il progetto in locale
		elimina.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				int ris = JOptionPane.showConfirmDialog(null, "Vuoi eliminare questo progetto?");
				if (ris == 0) {
					Properties pc = System.getProperties();
					String homePath = pc.getProperty("user.home");
					String directoryProject = homePath + pc.getProperty("file.separator") + "ArchimedeSuper" + pc.getProperty("file.separator")
							+ nameProject;
					File dirtmp = new File(directoryProject);
					if (dirtmp.exists()) {
						try {
							// System.out.println("to delete ------> " + directoryProject);
							FileUtils.forceDelete(dirtmp);
						} catch (IOException e) {
							// System.out.println("error ------> " + directoryProject);
							e.printStackTrace();
						}
					}
					directoryProject = directoryProject + "_delete";
					dirtmp = new File(directoryProject);
					dirtmp.setWritable(false);
					dirtmp.mkdir();
					nuovo();
					setProjectListFromPC();
				}

			}
		});

		nuovo.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				nuovo();
			}
		});

		download.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				setProjectListFromPC();
				new Credenziali();
			}
		});

		menubar.add(new JSeparator(SwingConstants.VERTICAL));
		menubar.add(download);
		menubar.add(new JSeparator(SwingConstants.VERTICAL));
		menubar.add(salva);
		menubar.add(new JSeparator(SwingConstants.VERTICAL));
		menubar.add(invia);
		menubar.add(new JSeparator(SwingConstants.VERTICAL));
		menubar.add(elimina);
		menubar.add(new JSeparator(SwingConstants.VERTICAL));
		menubar.add(nuovo);
	}

	/**
	 * salvare i dati del progetto corrente in locale true=salvataggio riuscito , false=errore
	 */
	public boolean save() {

		// controllo se cambiato nome del progetto
		if (nameProject != null)
			if (!nameProject.equals(datiEdificio.getProgetto())) {
				System.out.println("------>  mod name " + datiEdificio.getProgetto() + " --- " + nameProject);
				premesse.replace(datiEdificio.getProgetto(), nameProject);
				rilevazione.replace(datiEdificio.getProgetto(), nameProject);
				critico.replace(datiEdificio.getProgetto(), nameProject);
				sali.replace(datiEdificio.getProgetto(), nameProject);
				orizzontali.replace(datiEdificio.getProgetto(), nameProject);
				verticali.replace(datiEdificio.getProgetto(), nameProject);
				conclusioni.replace(datiEdificio.getProgetto(), nameProject);
			}

		nameProject = datiEdificio.getProgetto();
		Properties pc = System.getProperties();
		String homePath = pc.getProperty("user.home");

		String directoryProject = homePath + pc.getProperty("file.separator") + "ArchimedeSuper" + pc.getProperty("file.separator")
				+ datiEdificio.getProgetto();
		// System.out.println("------> " + directoryProject);
		
		// creo directory del progetto
		File directory = new File(directoryProject);
		directory.mkdir();

		// creo le sotto cartelle di extra	
		File sub = new File(directoryProject + pc.getProperty("file.separator") + "extra");
		sub.mkdir();

		sub = new File(sub + pc.getProperty("file.separator") + "foto" + pc.getProperty("file.separator") + "punti_misurazione");
		sub.mkdirs();
		sub = new File(directoryProject + pc.getProperty("file.separator") + "extra" + pc.getProperty("file.separator") + "foto"
				+ pc.getProperty("file.separator") + "punti_critici");
		sub.mkdir();
		sub = new File(directoryProject + pc.getProperty("file.separator") + "extra" + pc.getProperty("file.separator") + "foto"
				+ pc.getProperty("file.separator") + "tensione_orizzontale");
		sub.mkdir();
		sub = new File(directoryProject + pc.getProperty("file.separator") + "extra" + pc.getProperty("file.separator") + "foto"
				+ pc.getProperty("file.separator") + "tensione_verticale");
		sub.mkdir();
		sub = new File(directoryProject + pc.getProperty("file.separator") + "extra" + pc.getProperty("file.separator") + "foto"
				+ pc.getProperty("file.separator") + "premesse");
		sub.mkdir();
		sub = new File(directoryProject + pc.getProperty("file.separator") + "extra" + pc.getProperty("file.separator") + "foto"
				+ pc.getProperty("file.separator") + "sali");
		sub.mkdir();
		sub = new File(directoryProject + pc.getProperty("file.separator") + "extra" + pc.getProperty("file.separator") + "foto"
				+ pc.getProperty("file.separator") + "pianta");
		sub.mkdir();

		sub = new File(directoryProject + pc.getProperty("file.separator") + "extra" + pc.getProperty("file.separator") + "cliente_collaboratore");
		sub.mkdir();

		sub = new File(directoryProject + pc.getProperty("file.separator") + "extra" + pc.getProperty("file.separator") + "documenti");
		sub.mkdir();

		sub = new File(directoryProject + pc.getProperty("file.separator") + "extra" + pc.getProperty("file.separator") + "termografia");
		sub.mkdir();

		sub = new File(directoryProject + pc.getProperty("file.separator") + "extra" + pc.getProperty("file.separator") + "termografia"
				+ pc.getProperty("file.separator") + "premesse");
		sub.mkdir();

		sub = new File(directoryProject + pc.getProperty("file.separator") + "extra" + pc.getProperty("file.separator") + "termografia"
				+ pc.getProperty("file.separator") + "punti_misurazione");
		sub.mkdir();

		sub = new File(directoryProject + pc.getProperty("file.separator") + "extra" + pc.getProperty("file.separator") + "termografia"
				+ pc.getProperty("file.separator") + "punti_critici");
		sub.mkdir();

		//salvo i dati
		File fileSave = new File(directoryProject + pc.getProperty("file.separator") + countRtd + ".txt");
		try {
			fileSave.renameTo(new File(directoryProject + pc.getProperty("file.separator") + "last.txt"));
			fileSave.createNewFile();
			try {
				FileWriter fw = new FileWriter(fileSave);
				BufferedWriter bw = new BufferedWriter(fw);
				PrintWriter outFile = new PrintWriter(bw);

				String print = datiEdificio.print();
				print = print + premesse.print();
				print = print + strumenti.print();
				print = print + rilevazione.print();
				print = print + critico.print();
				print = print + sali.print();
				print = print + conclusioni.print();
				print = print + piantina.print();
				print = print + verticali.print();
				print = print + orizzontali.print();
				outFile.println(print);

				outFile.close();

				// salvo foto
				boolean error = false;
				String errorString = "";
				if (!premesse.save()) {
					error = true;
					errorString = "Errore foto in premesse";
				}
				if (!rilevazione.save()) {
					error = true;
					errorString = errorString + "/nErrore foto in punti di rilevazione";
				}
				if (!critico.save()) {
					error = true;
					errorString = errorString + "/nErrore foto in punti critici";
				}

				if (!sali.save()) {
					error = true;
					errorString = errorString + "/nErrore foto in sali";
				}
				if (!orizzontali.save()) {
					error = true;
					errorString = errorString + "/nErrore foto in orizzontali";
				}
				if (!verticali.save()) {
					error = true;
					errorString = errorString + "/nErrore foto in verticali";
				}
				if (!conclusioni.save()) {
					error = true;
					errorString = errorString + "/nErrore foto in conclusioni";
				}

				piantina.save();

				// se c'è errore segnalo e provo a salvare le altre foto
				if (error) {
					JOptionPane.showMessageDialog(null, errorString);
					refresh();
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					save();
				}

			} catch (FileNotFoundException e1) {
				JOptionPane.showMessageDialog(null, "Riprova errore nella modifica del file. La versione precedente è stata salvata");
				e1.printStackTrace();
				return false;
			} catch (IOException e) {
				JOptionPane.showMessageDialog(null, "Riprova errore nella modifica del file. La versione precedente è stata salvata");
				e.printStackTrace();
				return false;
			}
		} catch (IOException e2) {
			JOptionPane.showMessageDialog(null, "Riprova errore nella crezione del file. La versione precedente è stata salvata");
			e2.printStackTrace();
			return false;
		}
		return true;

	}
	/**
	 * classe interna per aprire il progetto selezionato a caricare i dati salvati dal server
	 * 
	 * @author Alex
	 * 
	 */
	private class Open implements ActionListener {
		/**
		 * numero progetto
		 */
		private int n;
		/**
		 * nome del progetto
		 */
		private String progetto;

		Open(String name) {
			progetto = name;
			try {
				n = Integer.parseInt(name.substring(0, 3));
			} catch (Exception e) {
				try {
					n = Integer.parseInt(name.substring(0, 2));
				} catch (Exception e2) {
					try {
						n = Integer.parseInt(name.substring(0, 1));
					} catch (Exception e3) {
						n = 0;
					}
				}
			}

			// System.out.println("addActionListener " + n);
		}

		public void actionPerformed(ActionEvent e) {
			nuovo();
			countRtd = n;
			nameProject = progetto;
			System.out.println("------@ " + nameProject + "  -  " + countRtd);
			// reset dati precedenti

			// caricamento file
			FTPClient client = new FTPClient();
			try {

				// connessione
				client.connect("83.211.158.68");
				// login
				client.login(username, password);

				// mi sposto nel progetto
				client.changeDirectory(progetto);
				// dentro eureka ho i dati del progetto
				client.changeDirectory("eureka");

				// trova la home del PC
				Properties pc = System.getProperties();
				String homePath = pc.getProperty("user.home");
				String directoryProject = homePath + pc.getProperty("file.separator") + "ArchimedeSuper" + pc.getProperty("file.separator") + progetto;

				// se c'è scovrascivo il progetto
				File dirtmp = new File(directoryProject);
				if (dirtmp.exists()) {
					FileUtils.forceDelete(dirtmp);
				}
				dirtmp.mkdir();

				// download
				try {
					// eureka
					FTPFile[] list = client.list();
					for (int i = 0; i < list.length; i++) {
						// System.out.println(list[i].getName());
						client.download(list[i].getName(), new File(directoryProject + pc.getProperty("file.separator") + list[i].getName()));

					}
					// // mi sposto in extra
					// client.changeDirectoryUp();
					// client.changeDirectory("extra");
					// dirtmp = new File(directoryProject + pc.getProperty("file.separator") + "extra");
					// dirtmp.mkdir();
					// list = client.list();
					// // extra
					// for (int i = 0; i < list.length; i++) {
					// // System.out.println(list[i].getName());
					// client.download(
					// list[i].getName(),
					// new File(directoryProject + pc.getProperty("file.separator") + "extra" + pc.getProperty("file.separator") + list[i].getName()));
					// }
					// op.showMessageDialog(null, "DOWNLOAD TERMINATO");
				} catch (Throwable e2) {
					JOptionPane.showMessageDialog(null, "Errore nel download, premere nuovamente download e inserire credenziali");
					e2.printStackTrace();
				}

				// client.logout();
				client.disconnect(true);
				// System.out.println("logout");

				// file di salvataggio
				String filePath = directoryProject + pc.getProperty("file.separator") + countRtd + ".txt";

				// prendo i dati dal file .txt
				File toScan = new File(filePath);

				try {
					Scanner c = new Scanner(toScan);
					int index = 0;
					String done = "";
					while (c.hasNextLine()) {
						String tmp = c.nextLine();
						if (tmp.contains("@@")) {
							setField(index, done);
							done = "";
							index++;

						} else
							done = done + "\n" + tmp;
					}
					c.close();

				} catch (FileNotFoundException e1) {

					e1.printStackTrace();
				}

			} catch (IllegalStateException e2) {
				JOptionPane.showMessageDialog(null, "Errore nel download, premere nuovamente download e inserire credenziali");
				e2.printStackTrace();
			} catch (IOException e2) {
				JOptionPane.showMessageDialog(null, "Errore nel download, premere nuovamente download e inserire credenziali");
				e2.printStackTrace();
			} catch (FTPIllegalReplyException e2) {
				JOptionPane.showMessageDialog(null, "Errore nel download, premere nuovamente download e inserire credenziali");
				e2.printStackTrace();
			} catch (FTPException e2) {
				JOptionPane.showMessageDialog(null, "Errore nel download, premere nuovamente download e inserire credenziali");
				e2.printStackTrace();
			}

			window.setTitle("EUREKA SILVER - ARCHIMEDE" + " ~ Progetto " + countRtd);

		}

		public void setField(int index, String content) {
			if (index == 0)
				datiEdificio.setFields(content);
			else if (index == 1)
				premesse.setElement(content);
			else if (index == 2)
				strumenti.setElement(content);
			else if (index == 3)
				rilevazione.setElement(content);
			else if (index == 4)
				critico.setElement(content);
			else if (index == 5)
				sali.setElement(content);
			else if (index == 6)
				conclusioni.setElement(content);
			else if (index == 7)
				conclusioni.setProfessionista(content);

			else if (index == 8)
				piantina.setElement(content);
			else if (index == 9)
				verticali.setElement(content);
			else if (index == 10)
				orizzontali.setElement(content);
		}
	}

	/**
	 * carica il progetto in locale
	 * 
	 * @author tomaseo
	 * 
	 */
	private class LoadProject implements ActionListener {
		/**
		 * numero progetto
		 */
		private int n;
		/**
		 * nome del progetto
		 */
		private String progetto;

		LoadProject(String name) {
			progetto = name;
			try {
				n = Integer.parseInt(name.substring(0, 3));
			} catch (Exception e) {
				try {
					n = Integer.parseInt(name.substring(0, 2));
				} catch (Exception e2) {
					try {
						n = Integer.parseInt(name.substring(0, 1));
					} catch (Exception e3) {
						n = 0;
					}
				}
			}

			// System.out.println("addActionListener " + n);
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			nuovo();
			countRtd = n;
			nameProject = progetto;
			System.out.println("------## " + nameProject + "  -  " + countRtd);
			Properties pc = System.getProperties();
			String homePath = pc.getProperty("user.home");
			String directoryProject = homePath + pc.getProperty("file.separator") + "ArchimedeSuper" + pc.getProperty("file.separator") + progetto;

			// file di salvataggio
			String filePath = directoryProject + pc.getProperty("file.separator") + countRtd + ".txt";

			File toScan = new File(filePath);

			try {
				Scanner c = new Scanner(toScan);
				int index = 0;
				String done = "";
				while (c.hasNextLine()) {
					String tmp = c.nextLine();
					if (tmp.contains("@@")) {
						setField(index, done);
						done = "";
						index++;

					} else
						done = done + "\n" + tmp;
				}
				c.close();

			} catch (FileNotFoundException e1) {

				e1.printStackTrace();
			}
			window.setTitle("EUREKA SILVER - ARCHIMEDE" + " ~ Progetto " + countRtd);
		}

		public void setField(int index, String content) {
			if (index == 0)
				datiEdificio.setFields(content);
			else if (index == 1)
				premesse.setElement(content);
			else if (index == 2)
				strumenti.setElement(content);
			else if (index == 3)
				rilevazione.setElement(content);
			else if (index == 4)
				critico.setElement(content);
			else if (index == 5)
				sali.setElement(content);
			else if (index == 6)
				conclusioni.setElement(content);
			else if (index == 7)
				conclusioni.setProfessionista(content);

			else if (index == 8)
				piantina.setElement(content);
			else if (index == 9)
				verticali.setElement(content);
			else if (index == 10)
				orizzontali.setElement(content);
		}

	}

	/**
	 * entra nel server e carica la lista presenti nel database, salva le credenziali per il download vero e proprio
	 * 
	 * @author tomaseo
	 * 
	 */
	private class Credenziali extends JFrame {
		/**
		 * server
		 */
		private FTPClient client = new FTPClient();

		/**
		 * insert user
		 */
		private JTextField user = new JTextField() {
			protected void paintComponent(Graphics g) {
				if (!isOpaque()) {
					int w = getWidth();
					int h = getHeight();
					Graphics2D g2 = (Graphics2D) g.create();
					g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
					g2.setColor(UIManager.getColor("TextField.background"));
					g2.fillRoundRect(0, 0, w - 2, h - 2, 10, 10);
					g2.setColor(Color.BLACK);
					g2.drawRoundRect(0, 0, w - 2, h - 2, 10, 10);
					g2.dispose();
				}
				super.paintComponent(g);
			}
		};

		/**
		 * insert pwd
		 */
		private JPasswordField pwd = new JPasswordField() {
			protected void paintComponent(Graphics g) {
				if (!isOpaque()) {
					int w = getWidth();
					int h = getHeight();
					Graphics2D g2 = (Graphics2D) g.create();
					g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
					g2.setColor(UIManager.getColor("TextField.background"));
					g2.fillRoundRect(0, 0, w - 2, h - 2, 10, 10);
					g2.setColor(Color.BLACK);
					g2.drawRoundRect(0, 0, w - 2, h - 2, 10, 10);
					g2.dispose();
				}
				super.paintComponent(g);
			}
		};
		/**
		 * confirm button
		 */
		private JButton ok = new JButton("   entra   ");

		public Credenziali() {
			try {
				UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
			} catch (UnsupportedLookAndFeelException localUnsupportedLookAndFeelException) {
			} catch (ClassNotFoundException localClassNotFoundException) {
			} catch (InstantiationException localInstantiationException) {
			} catch (IllegalAccessException localIllegalAccessException) {
			}
			setLayout(new MigLayout());

			pwd.addKeyListener(new KeyListener() {

				@Override
				public void keyTyped(KeyEvent arg0) {

				}

				@Override
				public void keyReleased(KeyEvent arg0) {
					// TODO Auto-generated method stub

				}

				@Override
				public void keyPressed(KeyEvent arg0) {
					if (arg0.getKeyCode() == KeyEvent.VK_ENTER) {
						// try {
						password = new String(pwd.getPassword());
						username = user.getText();

						FTPClient client = new FTPClient();
						try {
							// connessione
							client.connect("83.211.158.68");
							// login
							client.login(username, password);

							// lista cartelle presenti
							FTPFile[] list = client.list();
							for (int i = 0; i < list.length; i++) {
								// cerco solo le cartelle e le aggiungo al menu
								if (list[i].getType() == FTPFile.TYPE_DIRECTORY) {
									try {
										JMenuItem tp = new JMenuItem(list[i].getName());
										// System.out.println("<<" + list[i].getName());
										tp.addActionListener(new Open(list[i].getName()));
										tp.setForeground(Color.RED);
										apriProgetto.add(tp);
									} catch (Exception e) {
										// non contiene più il progetto
									}

								}
							}
							// logout
							// client.logout();
							// libero il server
							client.disconnect(true);

							Credenziali.this.setVisible(false);

						} catch (IllegalStateException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} catch (FTPIllegalReplyException e1) {
							JOptionPane.showMessageDialog(null, "Errore nella connessione , riprova");
							pwd.setText("");
							e1.printStackTrace();
						} catch (FTPException e1) {
							JOptionPane.showMessageDialog(null, "Errore nella connessione, riprova");
							pwd.setText("");
							e1.printStackTrace();
						} catch (FTPDataTransferException e) {
							JOptionPane.showMessageDialog(null, "Errore nella connessione, riprova");
							pwd.setText("");
							e.printStackTrace();
						} catch (FTPAbortedException e) {
							JOptionPane.showMessageDialog(null, "Errore nella connessione, riprova");
							pwd.setText("");
							e.printStackTrace();
						} catch (FTPListParseException e) {
							JOptionPane.showMessageDialog(null, "Errore nella connessione, riprova");
							pwd.setText("");
							e.printStackTrace();
						}
					}

				}
			});

			ok.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					password = new String(pwd.getPassword());
					username = user.getText();

					FTPClient client = new FTPClient();
					try {
						// connessione
						client.connect("83.211.158.68");
						// login
						client.login(username, password);

						// lista cartelle presenti
						FTPFile[] list = client.list();
						for (int i = 0; i < list.length; i++) {
							// cerco solo le cartelle e le aggiungo al menu
							if (list[i].getType() == FTPFile.TYPE_DIRECTORY) {
								try {
									JMenuItem tp = new JMenuItem(list[i].getName());
									// System.out.println("<<" + list[i].getName());
									tp.addActionListener(new Open(list[i].getName()));
									tp.setForeground(Color.RED);
									apriProgetto.add(tp);
								} catch (Exception e) {
									// non contiene più il progetto
								}

							}
						}
						// logout
						// client.logout();
						// libero il server
						client.disconnect(true);

						Credenziali.this.setVisible(false);

					} catch (IllegalStateException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (FTPIllegalReplyException e1) {
						JOptionPane.showMessageDialog(null, "Errore nella connessione , riprova");
						pwd.setText("");
						e1.printStackTrace();
					} catch (FTPException e1) {
						JOptionPane.showMessageDialog(null, "Errore nella connessione, riprova");
						pwd.setText("");
						e1.printStackTrace();
					} catch (FTPDataTransferException e) {
						JOptionPane.showMessageDialog(null, "Errore nella connessione, riprova");
						pwd.setText("");
						e.printStackTrace();
					} catch (FTPAbortedException e) {
						JOptionPane.showMessageDialog(null, "Errore nella connessione, riprova");
						pwd.setText("");
						e.printStackTrace();
					} catch (FTPListParseException e) {
						JOptionPane.showMessageDialog(null, "Errore nella connessione, riprova");
						pwd.setText("");
						e.printStackTrace();
					}
				}
			});
			user.setOpaque(false);
			user.setBorder(BorderFactory.createEmptyBorder(4, 8, 4, 8));
			user.setPreferredSize(new Dimension(100, 30));
			pwd.setOpaque(false);
			pwd.setBorder(BorderFactory.createEmptyBorder(4, 8, 4, 8));
			pwd.setPreferredSize(new Dimension(100, 30));
			add(new JLabel("User"));
			add(user);
			add(new JLabel("Password"));
			add(pwd);
			add(ok, "wrap");
			add(new JLabel("L'operazione di connessione al server può durare diversi secondi"), "dock south");
			add(new JLabel("Una volta selezionato il progetto attendere il download"), "dock south");

			setVisible(true);
			pack();
			setLocation(300, 200);
		}
	}

	/**
	 * @param path
	 *           :percorso assoluto dell'ultimo file caricato
	 */
	public void setPath(String path) {
		lastPath = path;
	}

	/**
	 * 
	 * @return percorso assoluto dell'ultimo file caricato
	 */
	public String getPath() {
		return lastPath;
	}

	/**
	 * 
	 * @return larghezza schermo
	 */
	public int getWidth() {
		return width;
	}

	/**
	 * 
	 * @return altezza schermo
	 */
	public int getHeight() {
		return height;
	}

	/**
	 * 
	 * @return valore rtd corrente
	 */
	public int getCount() {
		return countRtd;
	}

	private JFrame getWIndow() {
		return window;
	}

	/**
	 * 
	 * @return valore rtd corrente
	 */
	public String getProject() {
		return nameProject;
	}

	/**
	 * invia progetto al database
	 * 
	 * @author tomaseo
	 * 
	 */
	private class InviaProgetto extends JFrame {
		/**
		 * server
		 */
		private FTPClient client = new FTPClient();

		/**
		 * insert user
		 */
		private JTextField user = new JTextField() {
			protected void paintComponent(Graphics g) {
				if (!isOpaque()) {
					int w = getWidth();
					int h = getHeight();
					Graphics2D g2 = (Graphics2D) g.create();
					g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
					g2.setColor(UIManager.getColor("TextField.background"));
					g2.fillRoundRect(0, 0, w - 2, h - 2, 10, 10);
					g2.setColor(Color.BLACK);
					g2.drawRoundRect(0, 0, w - 2, h - 2, 10, 10);
					g2.dispose();
				}
				super.paintComponent(g);
			}
		};

		/**
		 * insert pwd
		 */
		private JPasswordField pwd = new JPasswordField() {
			protected void paintComponent(Graphics g) {
				if (!isOpaque()) {
					int w = getWidth();
					int h = getHeight();
					Graphics2D g2 = (Graphics2D) g.create();
					g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
					g2.setColor(UIManager.getColor("TextField.background"));
					g2.fillRoundRect(0, 0, w - 2, h - 2, 10, 10);
					g2.setColor(Color.BLACK);
					g2.drawRoundRect(0, 0, w - 2, h - 2, 10, 10);
					g2.dispose();
				}
				super.paintComponent(g);
			}
		};
		private JButton ok = new JButton("   entra   ");

		public InviaProgetto(final String path) {
			try {
				UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
			} catch (UnsupportedLookAndFeelException localUnsupportedLookAndFeelException) {
			} catch (ClassNotFoundException localClassNotFoundException) {
			} catch (InstantiationException localInstantiationException) {
			} catch (IllegalAccessException localIllegalAccessException) {
			}
			setLayout(new MigLayout());

			pwd.addKeyListener(new KeyListener() {

				@Override
				public void keyTyped(KeyEvent arg0) {

				}

				@Override
				public void keyReleased(KeyEvent arg0) {
					// TODO Auto-generated method stub

				}

				@Override
				public void keyPressed(KeyEvent arg0) {
					if (arg0.getKeyCode() == KeyEvent.VK_ENTER) {
						// try {
						password = new String(pwd.getPassword());
						username = user.getText();

						FTPClient client = new FTPClient();
						try {
							// connessione
							client.connect("83.211.158.68");
							// login
							client.login(username, password);

							try {
								client.changeDirectory(nameProject);
								try {
									client.changeDirectory("eureka");
									FTPFile[] fileToDelete = client.list();
									for (int i = 0; i < fileToDelete.length; i++)
										client.deleteFile(fileToDelete[i].getName());
								} catch (Exception e) {
									e.printStackTrace();
								}
							} catch (Exception e) {
								client.createDirectory(nameProject);
								client.changeDirectory(nameProject);
								client.createDirectory("eureka");
								client.createDirectory("extra");
								client.changeDirectory("eureka");
							}

							// cartella di progetto da caricare solo EUREKA
							File dir = new File(path);
							File[] fileDir = dir.listFiles();

							for (int i = 0; i < fileDir.length; i++) {
								if (fileDir[i].isFile())
									client.upload(fileDir[i]);
							}

							InviaProgetto.this.setVisible(false);

							int risposta = JOptionPane.showConfirmDialog(null, "Progetto inviato, inviare allegati?");
							// si
							if (risposta == 0) {
								JFileChooser chooser = new JFileChooser();

								// Enable multiple selections
								chooser.setMultiSelectionEnabled(true);

								// Show the dialog; wait until dialog is closed
								if (lastPath.equals(""))
									chooser.getCurrentDirectory();
								else
									chooser.setCurrentDirectory(new File(lastPath));
								chooser.showOpenDialog(getWIndow());

								// Retrieve the selected files. This method returns empty
								// if multiple-selection mode is not enabled.
								File[] files = chooser.getSelectedFiles();

								client.changeDirectoryUp();
								client.changeDirectory("extra");
								try {
									client.createDirectory("cliente_collaboratore");
								} catch (Exception e) {

								}
								client.changeDirectory("cliente_collaboratore");
								for (int i = 0; i < files.length; i++) {
									client.upload(files[i]);
								}
								// logout
								// client.logout();
								// libero il server
								client.disconnect(true);
							} else {
								// logout
								// client.logout();
								// libero il server
								client.disconnect(true);
							}

						} catch (IllegalStateException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} catch (FTPIllegalReplyException e1) {
							JOptionPane.showMessageDialog(null, "Errore nella connessione , riprova");
							pwd.setText("");
							e1.printStackTrace();
						} catch (FTPException e1) {
							JOptionPane.showMessageDialog(null, "Errore nella connessione , riprova");
							pwd.setText("");
							e1.printStackTrace();
						} catch (FTPDataTransferException e) {
							JOptionPane.showMessageDialog(null, "Errore nella connessione , riprova");
							pwd.setText("");
							e.printStackTrace();
						} catch (FTPAbortedException e) {
							JOptionPane.showMessageDialog(null, "Errore nella connessione , riprova");
							pwd.setText("");
							e.printStackTrace();
						}
					}

				}
			});

			ok.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					password = new String(pwd.getPassword());
					username = user.getText();

					FTPClient client = new FTPClient();
					try {
						// connessione
						client.connect("83.211.158.68");
						// login
						client.login(username, password);

						try {
							client.changeDirectory(nameProject);
							try {
								client.changeDirectory("eureka");
								FTPFile[] fileToDelete = client.list();
								for (int i = 0; i < fileToDelete.length; i++)
									client.deleteFile(fileToDelete[i].getName());
							} catch (Exception e) {
								e.printStackTrace();
							}
						} catch (Exception e) {
							client.createDirectory(nameProject);
							client.changeDirectory(nameProject);
							client.createDirectory("eureka");
							client.createDirectory("extra");
							client.changeDirectory("eureka");
						}

						// cartella di progetto da caricare solo EUREKA
						File dir = new File(path);
						File[] fileDir = dir.listFiles();

						for (int i = 0; i < fileDir.length; i++) {
							if (fileDir[i].isFile())
								client.upload(fileDir[i]);
						}

						InviaProgetto.this.setVisible(false);

						int risposta = JOptionPane.showConfirmDialog(null, "Progetto inviato, inviare allegati?");
						// si
						if (risposta == 0) {
							JFileChooser chooser = new JFileChooser();

							// Enable multiple selections
							chooser.setMultiSelectionEnabled(true);

							// Show the dialog; wait until dialog is closed
							if (lastPath.equals(""))
								chooser.getCurrentDirectory();
							else
								chooser.setCurrentDirectory(new File(lastPath));
							chooser.showOpenDialog(getWIndow());

							// Retrieve the selected files. This method returns empty
							// if multiple-selection mode is not enabled.
							File[] files = chooser.getSelectedFiles();

							client.changeDirectoryUp();
							client.changeDirectory("extra");
							try {
								client.createDirectory("cliente_collaboratore");
							} catch (Exception e) {

							}
							client.changeDirectory("cliente_collaboratore");
							for (int i = 0; i < files.length; i++) {
								client.upload(files[i]);
							}

						} // logout
							// client.logout();
							// libero il server
						client.disconnect(true);

					} catch (IllegalStateException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (FTPIllegalReplyException e1) {
						JOptionPane.showMessageDialog(null, "Errore nella connessione , riprova");
						pwd.setText("");
						e1.printStackTrace();
					} catch (FTPException e1) {
						JOptionPane.showMessageDialog(null, "Errore nella connessione , riprova");
						pwd.setText("");
						e1.printStackTrace();
					} catch (FTPDataTransferException e) {
						JOptionPane.showMessageDialog(null, "Errore nella connessione , riprova");
						pwd.setText("");
						e.printStackTrace();
					} catch (FTPAbortedException e) {
						JOptionPane.showMessageDialog(null, "Errore nella connessione , riprova");
						pwd.setText("");
						e.printStackTrace();
					}
				}
			});
			user.setOpaque(false);
			user.setBorder(BorderFactory.createEmptyBorder(4, 8, 4, 8));
			user.setPreferredSize(new Dimension(100, 30));
			pwd.setOpaque(false);
			pwd.setBorder(BorderFactory.createEmptyBorder(4, 8, 4, 8));
			pwd.setPreferredSize(new Dimension(100, 30));
			add(new JLabel("User"));
			add(user);
			add(new JLabel("Password"));
			add(pwd);
			add(ok, "wrap");
			add(new JLabel("L'operazione di connessione al server può durare diversi secondi"), "dock south");

			setVisible(true);
			pack();
			setLocation(300, 200);
		}
	}

	/**
	 * alla chiusura chiedere se salvare file
	 * 
	 * @author tomaseo
	 * 
	 */
	private class WindowsClosing implements WindowListener {

		@Override
		public void windowOpened(WindowEvent e) {
			// TODO Auto-generated method stub

		}

		@Override
		public void windowClosing(WindowEvent e) {
			int risposta = JOptionPane.showConfirmDialog(null, "Salvare il progetto?");
			if (risposta == 0) {
				save();
				System.exit(0);

			} else if (risposta == 1) {
				System.exit(0);
			}

		}

		@Override
		public void windowClosed(WindowEvent e) {
			// TODO Auto-generated method stub

		}

		@Override
		public void windowIconified(WindowEvent e) {
			// TODO Auto-generated method stub

		}

		@Override
		public void windowDeiconified(WindowEvent e) {
			// TODO Auto-generated method stub

		}

		@Override
		public void windowActivated(WindowEvent e) {
			// TODO Auto-generated method stub

		}

		@Override
		public void windowDeactivated(WindowEvent e) {
			// TODO Auto-generated method stub

		}

	}

	/**
	 * main
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		try {
			// Set System L&F
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (UnsupportedLookAndFeelException e) {
			// handle exception
		} catch (ClassNotFoundException e) {
			// handle exception
		} catch (InstantiationException e) {
			// handle exception
		} catch (IllegalAccessException e) {
			// handle exception
		}
		new StartingWindow();
	}

}